package config;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

public class ConfigLoader {
	
	private static ConfigLoader configLoader;
	private String host;
	private int port;
	private ConfigLoader(String filename) throws IOException, NumberFormatException {
		URL url = this.getClass().getResource(filename);
		BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
		String line;
		while((line = reader.readLine())!=null) {
			//System.out.println(readKey(line)+"____"+readValue(line));
			if(readKey(line).equals("SERVER")) {
				host = readValue(line);
			}
			else if (readKey(line).equals("PORT")) {
				port = Integer.parseInt(readValue(line));
			}
		}
		System.out.println(host+" "+port);
	}
	private String readValue(String line) {
		char[] value = new char[30];
		int i = 0;
		while(line.charAt(i) != '\t' && line.charAt(i) != ' ') {
			i++;
		}
		while(line.charAt(i) == '\t' || line.charAt(i) == ' ') {
			i++;
		}
		int k = 0;
		for(;i<line.length(); i++) {
			value[k++] = line.charAt(i);
		}
		return new String(value).trim();
	}
	private String readKey(String line) {
		char[] key = new char[20];
		for(int i = 1; i < line.length(); i++) {
			if(line.charAt(i) == ']') break;
			key[i-1] = line.charAt(i);
		}
		return new String(key).trim();
	}
	public static ConfigLoader getInstance(String filename) throws IOException {
		if(configLoader == null) configLoader = new ConfigLoader(filename);
		return configLoader;
	}
	public String getHost() {
		return host;
	}
	public void setHost(String host) {
		this.host = host;
	}
	public int getPort() {
		return port;
	}
	public void setPort(int port) {
		this.port = port;
	}
}
